<?php
/**
 * Created by PhpStorm.
 * User: Ann
 * Date: 2018/4/11
 * Time: 21:55
 */

namespace App\Http\Controllers;


use Log;
use EasyWeChat\Factory;

class WechatController extends Controller
{
    const TOKEN = 'testwechat';

    public function test()
    {
        $sPostData = file_get_contents('php://input');

        Log::info(['message' => $sPostData]); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志

        if (isset($_GET["echostr"])){

            if ($this->checkSignature()) {
                return $_GET['echostr'];
            }

        } else {

            $app = app('wechat.official_account');
            $app->server->push(function($message){
                return "欢迎关注 overtrue！\n换行了";
            });

            return $app->server->serve();
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = self::TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature){
            return true;
        }else {
            return false;
        }
    }

}